package com.deyuanyun.pic.pbf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.deyuanyun.pic.common.util.MapUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.insp.service.inspresult.InspCommService;
import com.deyuanyun.pic.insp.util.InspTaskVO;
import com.deyuanyun.pic.pbf.mapper.FocuMapper;
import com.deyuanyun.pic.pbf.service.FocuService;
import com.deyuanyun.pic.settings.controller.dto.BizMsgThresholdVO;
import com.deyuanyun.pic.settings.enumeration.ThresholdType;
import com.deyuanyun.pic.settings.service.base.BizMsgThresholdService;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 重点关注
 *
 * @author scalpel.王敏
 * @version [v1.0] 创建时间（2016/6/15）
 * @see // 引用的类
 * Method List:
 * 1.----------------
 * 2.----------------
 * History:
 */
@Service
public class FocuServiceImpl implements FocuService {


    @Resource
    private FocuMapper focuMapper;

    @Resource
    private InspCommService inspCommService;

    @Resource
    private BizMsgThresholdService bizMsgThresholdService;

    @Override
    public Map<String, Object> query(Map<String, String> param) {


        String lineId = param.get("lineId");
        String beginMileage = param.get("beginMileage");
        String endMileage = param.get("endMileage");
        List<InspTaskVO>  data = inspCommService.queryNewTaskMileage(lineId, StringUtils.isEmpty(beginMileage)?null:Double.parseDouble(beginMileage),StringUtils.isEmpty(endMileage)?null:Double.parseDouble(endMileage));

        Map<String,Object> result=new HashMap<String,Object>();
        String types[]={"jsss","ox","tybx","llw","ss","hfyc","直焊缝"};
        Map<String,BigDecimal> t =null;
        Map tm = new HashMap();
        tm.putAll(param);
        for (int i=0;i<5;i++)
        {
            t = null;
            tm.put("type",""+i);


            for(InspTaskVO itv:data)
            {
                tm.put("taskId",itv.getId());
                tm.put("beginMileage",itv.getFromMileage().toString());
                tm.put("endMileage",itv.getToMileage().toString());
                if(t == null)
                {
                    t = focuMapper.queryData(tm);
                }else{
                    MapUtil.mergeAdd(t,focuMapper.queryData(tm));
                }

            }
            result.put(types[i],t);
        }
        Map<String,BigDecimal> dmap= (Map<String, BigDecimal>) result.get("ox");



        //查询凹陷大于6%的缺陷数量
        BigDecimal oxGt6 = new BigDecimal(0);
        for(InspTaskVO itv:data)
        {
            tm.put("taskId",itv.getId());
            tm.put("beginMileage",itv.getFromMileage().toString());
            tm.put("endMileage",itv.getToMileage().toString());

            oxGt6 = oxGt6.add(BigDecimal.valueOf(focuMapper.querDepressed(tm)));

        }
        dmap.put("gt6",oxGt6);

        //焊缝异常 ,需要将环焊缝和制管焊缝异常数量加起来
        t = null;
        for(InspTaskVO itv:data)
        {
            tm.put("taskId",itv.getId());
            tm.put("beginMileage",itv.getFromMileage().toString());
            tm.put("endMileage",itv.getToMileage().toString());
            if(t == null)
            {
                t = sum("5","6",tm);
            }else{
                MapUtil.mergeAdd(t,sum("5","6",tm));
            }

        }
        result.put(types[5],t);


        //阀值设置
        result.put("hint",getHint(tm,data));


        return result;
    }

    public Map<String, BigDecimal> sum(String type1,String type2,Map<String,String> param)
    {
        param.put("type",type1);
       Map<String,BigDecimal> val1= focuMapper.queryData(param);
        param.put("type",type2);
        Map<String,BigDecimal> val2= focuMapper.queryData(param);

        val1.put("ERF",val1.get("ERF").add(val2.get("ERF")));
        val1.put("LJWX",val1.get("LJWX").add(val2.get("LJWX")));
        val1.put("ZZWX",val1.get("ZZWX").add(val2.get("ZZWX")));
        val1.put("NYWX",val1.get("NYWX").add(val2.get("NYWX")));
        val1.put("WWX",val1.get("WWX").add(val2.get("WWX")));
        val1.put("NUM",val1.get("NUM").add(val2.get("NUM")));
        val1.put("YWX",val1.get("YWX").add(val2.get("YWX")));
        val1.put("DHG",val1.get("DHG").add(val2.get("DHG")));
        return val1;
    }



    private List getHint(Map<String, String> param,List<InspTaskVO>  itvData )
    {

        Map<String, Object> hintParam = new HashMap<String, Object>();
        hintParam.putAll(param);

        String lineId = param.get("lineId");
        hintParam.put("assessMentDate",focuMapper.queryAssessMentDate(lineId));

        List<JSONObject> hintList=new ArrayList<JSONObject>();
        //查询阀值设置的信息
        List<BizMsgThresholdVO> data=bizMsgThresholdService.queryDataByTypes(ThresholdType.DEFECT_METAL_LOSS.getValue(),ThresholdType.DEFECT_PIT.getValue(),ThresholdType.DEFECT_GIRTH_WELD.getValue(),ThresholdType.DEFECT_IMMEDIATE_REPAIR.getValue());
        for (BizMsgThresholdVO v: data)
        {

            if(null == v.getThresholdContent() || v.getThresholdContent().length() == 0)
            {
                continue;
            }

            JSONObject jobj= JSONObject.parseObject(v.getThresholdContent());
            if (ThresholdType.DEFECT_METAL_LOSS.getValue().equals(v.getType()))
            {
                //金属损失查询
                String msg="ERF>%d且位于高后果区%d地区的金属损失总个数:%d个";
                hintParam.put("type",ThresholdType.DEFECT_METAL_LOSS.getValue());
                hintParam.put("erf",""+jobj.getFloatValue("erf"));
                hintParam.put("areaLevel",""+jobj.getIntValue("areaLevel"));
                jobj.put("item","0");
                Integer num = 0;
                for(InspTaskVO itv:itvData)
                {
                    hintParam.put("taskId",itv.getId());
                    hintParam.put("beginMileage",itv.getFromMileage().toString());
                    hintParam.put("endMileage",itv.getToMileage().toString());

                    num += focuMapper.queryPushFocus(hintParam);

                }

                jobj.put("num",num);
                hintList.add(jobj);
            }else if(ThresholdType.DEFECT_PIT.getValue().equals(v.getType()))
            {
                String msg="ERF>%d且位于高后果区%d地区的金属损失总个数:%d个";
                //凹陷缺陷查询
                hintParam.put("type",ThresholdType.DEFECT_PIT.getValue());
                hintParam.put("depth",""+jobj.getFloatValue("depth"));
                hintParam.put("areaLevel",""+jobj.getIntValue("areaLevel"));


                Integer num = 0;
                for(InspTaskVO itv:itvData)
                {
                    hintParam.put("taskId",itv.getId());
                    hintParam.put("beginMileage",itv.getFromMileage().toString());
                    hintParam.put("endMileage",itv.getToMileage().toString());

                    num += focuMapper.queryPushFocus(hintParam);

                }
                jobj.put("num",num);

                jobj.put("item","1");
                hintList.add(jobj);
            }else if(ThresholdType.DEFECT_GIRTH_WELD.getValue().equals(v.getType()))
            {
                //环焊缝缺陷查询
                hintParam.put("type",ThresholdType.DEFECT_GIRTH_WELD.getValue());
                hintParam.put("length",""+jobj.getFloatValue("length"));
                hintParam.put("width",""+jobj.getFloatValue("width"));
                hintParam.put("areaLevel",""+jobj.getIntValue("areaLevel"));
                jobj.put("num",focuMapper.queryPushFocus(hintParam));
                hintParam.put("type","DEFECT_GIRTH_WELD_PIPE");

                Integer num = 0;
                for(InspTaskVO itv:itvData)
                {
                    hintParam.put("taskId",itv.getId());
                    hintParam.put("beginMileage",itv.getFromMileage().toString());
                    hintParam.put("endMileage",itv.getToMileage().toString());

                    num += focuMapper.queryPushFocus(hintParam);

                }
                jobj.put("num",jobj.getIntValue("num")+num);

                jobj.put("item","2");
                hintList.add(jobj);
            }else if(ThresholdType.DEFECT_IMMEDIATE_REPAIR.getValue().equals(v.getType()))
            {
                String defectTables[]={"PIC_INSP_DEFECT_DEPRESSED i","PIC_INSP_DEFECT_ELLIPTIC i ","PIC_INSP_DEFECT_CRACK i",
                "PIC_INSP_DEFECT_OTHER i","PIC_INSP_DEFECT_PIPE_WELD i"};//"PIC_INSP_METAL_EXTERNAL","PIC_INSP_PATCH",
                //总缺陷查询
                Integer num = 0;
                for(int i=0;i<itvData.size();i++)
                {
                    InspTaskVO itv = itvData.get(i);
                    hintParam.put("taskId",itv.getId());
                    param.put("beginMileage",itv.getFromMileage().toString());
                    param.put("endMileage",itv.getToMileage().toString());

                    List<QueryUtil> queryList=new ArrayList<QueryUtil>();
                    String codeId= CodeUtil.getCodeId("REPAIR_SUGGESTED","立即维修");
                    for (String defectTable:defectTables)
                    {
                        queryList.add(new QueryUtil(defectTable," and tdi.REPAIR_SUGGESTION = '"+codeId+"'"+getMileageWhere("i",param) ));
                    }
                    String erf=jobj.getString("erf");


                    queryList.add(new QueryUtil("PIC_INSP_DEFECT_GIRTH_WELD i  "," and tdi.REPAIR_SUGGESTION = '"+codeId+"'"+getMileageWhere("i",param)));
                    queryList.add(new QueryUtil("PIC_INSP_DEFECT_META_LOSS i","and ( i.erf >="+erf+" or tdi.erf>="+erf+" or tdi.REPAIR_SUGGESTION = '"+codeId+"')"+getMileageWhere("i",param)));
                    hintParam.putAll(hintParam);
                    hintParam.put("tables",queryList);





                    num += focuMapper.queryAllFocus(hintParam);

                }
                jobj.put("num",num);
                jobj.put("item","3");
                hintList.add(jobj);
            }

        }





        return  hintList;
    }


    /**
     *  获取里程查询参数
     * @param param
     * @return
     */
    public String getMileageWhere(String alias,Map<String,String> param)
    {
        String trim=" ";
        StringBuilder result=new StringBuilder();
        if(param.get("beginMileage") != null)
        {
            result.append(" and ").append(trim).append(alias).append(".MILEAGE >= ").append(param.get("beginMileage"));
        }
        if(param.get("endMileage") != null) {
            result.append(" and ").append(trim).append(alias).append(".MILEAGE < ").append(param.get("endMileage"));
        }
        return  result.toString();
    }


    class  QueryUtil
    {
        String table="";
        String where="";
        public QueryUtil(String table,String where)
        {
            this.table=table;
            this.where=where;
        }

        public String getTable() {
            return table;
        }

        public String getWhere() {
            return where;
        }
    }
}
